<template>
  <div class="app-container">
    用户设置

    <el-form label-width="120px">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item v-if="isAdd === true" label="用户账号">
            <el-input v-model="userSet.userAccount" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item v-if="isAdd === true" label="用户邮箱">
            <el-input v-model="userSet.userEmail" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item label="用户名">
            <el-input v-model="userSet.userName" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="checkPermission(['ROLE_superAdmin', 'ROLE_superAdmin'])" :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item label="用户类型">
            <el-select v-model="userSet.userType" placeholder="请选择用户类型">
              <el-option
                v-for="item in selectType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item v-if="isAdd === true" label="密码">
            <el-input v-model="userSet.password" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item label="头像">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              :action="fileUrl"
              :show-file-list="false"
              :on-change="beforeAvatarUpload"
              :data="userInfoObj"
              :headers="headersObj"
              :auto-upload="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<script>
import userApi from '@/api/userset'
import checkPermission from '@/utils/permission'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      userSet: {},
      isAdd: true,
      fileUrl: process.env.VUE_APP_BASE_API + '/admin/user/headPortrait',
      imageUrl: '',
      headersObj: {},
      userInfoObj: {},
      fileLength: 0,
      selectType: [
        {
          value: 0,
          label: '普通用户'
        },
        {
          value: 1,
          label: '审核员'
        },
        {
          value: 2,
          label: '管理员'
        }
      ]
    }
  },
  // 页面渲染之前执行
  created() {
    // 获取路由id值 调用接口得到信息
    if (this.$route.params && this.$route.params.id) {
      const id = this.$route.params.id
      this.isAdd = false
      this.getUserSet(id)
    }
  },
  mounted: function() {
    this.$nextTick(function() {
      // 元素加载完成后执行的代码
      this.headersObj['token'] = getToken()
    })
  },
  methods: {
    // 检查权限
    checkPermission,
    // 上传成功
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.$message({
        type: 'success',
        message: '头像上传成功!'
      })

      // 跳转列表页面，使用路由跳转方式实现
      this.$router.push({ path: '/userset/list' })
    },
    // 上传图片判断
    beforeAvatarUpload(file, fileList) {
      this.fileLength = fileList.length
      // const isJPG = file.type === 'image/jpeg';
      console.log(file.name)

      let isImage = this.isImage(file.name)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片!')
        isImage = false
      } else {
        isImage = true
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      if (isImage && isLt2M) {
        this.imageUrl = URL.createObjectURL(file.raw)
      }
      return isImage && isLt2M
    },
    // 是否是图片
    isImage(fileName) {
      if (typeof fileName !== 'string') return
      const name = fileName.toLowerCase()
      return (
        name.endsWith('.png') ||
        name.endsWith('.jpeg') ||
        name.endsWith('.jpg') ||
        name.endsWith('.png')
      )
    },
    // 添加
    saveOrUpdate() {
      // 判断添加还是修改
      if (!this.userSet.uid) {
        // 没有id，做添加
        this.save()
      } else {
        // 修改
        this.update()
      }
    },
    save() {
      if (this.fileLength === 0) {
        this.$message.error('请上传头像')
        return
      }

      userApi.saveUserSet(this.userSet).then((response) => {
        // 赋值
        this.userInfoObj.uid = response.data.uid
        // 提示
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
        // 上传文件
        this.$refs.upload.submit()
      })
      // .catch((response) => {
      //   //添加错误
      //   this.$message({
      //     type: "error",
      //     message: response.message,
      //   });
      // });
    },
    // 修改
    update() {
      userApi.updateUserSet(this.userSet).then(() => {
        // 提示
        this.$message({
          type: 'success',
          message: '修改成功!'
        })
        //  !=-1 为找到,则 已经更改头像
        if (this.imageUrl.search('blob:http') !== -1) {
          this.$refs.upload.submit()
        } else {
          // 跳转列表页面，使用路由跳转方式实现
          this.$router.push({ path: '/userset/list' })
        }
      })
    },

    // 根据id查询
    getUserSet(id) {
      userApi.getUser(id).then((response) => {
        this.userSet = response.data
        this.userInfoObj.uid = response.data.uid
        this.imageUrl = response.data.imageUrl
      })
    }
  }
}
</script>
